package cn.lzx.controller;

import cn.lzx.domain.JsonResult;
import cn.lzx.domain.MovieTicket;
import cn.lzx.domain.User;
import cn.lzx.dto.TicketInfo;
import cn.lzx.dto.UserMovieDto;
import cn.lzx.feign.MovieFeign;
import cn.lzx.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private MovieFeign movieFeign;

    @GetMapping("/findById/{id}")
    public JsonResult findById(@PathVariable("id") Long id){
        return movieFeign.findById(id);
    }

    @RequestMapping(value="/buyTicket",method= RequestMethod.POST)
    public JsonResult buyTicket(@RequestBody UserMovieDto userMovieDto){
        try {
            Object object = movieFeign.findById(userMovieDto.getMovieTicketId()).getObject();
            //电影信息
            MovieTicket movieTicket = JSON.parseObject(JSON.toJSONString(object), MovieTicket.class);
            userService.buyTicket(userMovieDto,movieTicket);
            movieFeign.buyTicket(userMovieDto);
            return new JsonResult(true,"购买电影票成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"购买电影票失败");
        }
    }

    @GetMapping("/movie/getTicket/{id}")
    public TicketInfo getTicket(@PathVariable("id") Long id){
        try {
            TicketInfo ticketInfo = userService.getTicket(id);
            return ticketInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return new TicketInfo();
        }
    }

    @PostMapping("/addUser")
    public JsonResult addUser(@RequestBody User user){
        try {
            userService.addUser(user);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"新增用户失败");
        }
    }







}
